package com.yf.exam.modules.sys.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.google.common.collect.Lists;
import com.yf.exam.core.api.ApiRest;
import com.yf.exam.core.api.controller.BaseController;
import com.yf.exam.core.api.dto.BaseIdsReqDTO;
import com.yf.exam.core.api.dto.BaseStateReqDTO;
import com.yf.exam.core.api.dto.PagingReqDTO;
import com.yf.exam.core.exception.ServiceException;
import com.yf.exam.core.utils.excel.ExportExcel;
import com.yf.exam.core.utils.excel.ImportExcel;
import com.yf.exam.modules.sys.depart.service.SysDepartService;
import com.yf.exam.modules.sys.user.dto.SysUserDTO;
import com.yf.exam.modules.sys.user.dto.UserDTO;
import com.yf.exam.modules.sys.user.dto.request.SysUserLoginReqDTO;
import com.yf.exam.modules.sys.user.dto.request.SysUserSaveReqDTO;
import com.yf.exam.modules.sys.user.dto.response.SysUserLoginDTO;
import com.yf.exam.modules.sys.user.entity.SysUser;
import com.yf.exam.modules.sys.user.service.SysUserService;
import com.yf.exam.modules.user.exam.dto.UserExamDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 管理用户控制器
 * </p>
 *
 * @author 聪明笨狗
 * @since 2020-04-13 16:57
 */
@Api(tags = {"管理用户"})
@RestController
@RequestMapping("/exam/api/sys/user")
public class SysUserController extends BaseController {
    @Autowired
    private SysUserService baseService;
    @Autowired
    private SysDepartService sysDepartService;


    /**
     * 用户登录
     * @return
     */
    @CrossOrigin
    @ApiOperation(value = "用户登录")
    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    public ApiRest<SysUserLoginDTO> login(@RequestBody SysUserLoginReqDTO reqDTO) {
        SysUserLoginDTO respDTO = baseService.login(reqDTO.getUsername(), reqDTO.getPassword());
        return super.success(respDTO);
    }

    /**
     * 用户登录
     * @return
     */
    @CrossOrigin
    @ApiOperation(value = "用户登录")
    @RequestMapping(value = "/logout", method = {RequestMethod.POST})
    public ApiRest logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        System.out.println("+++++当前会话为："+token);
        baseService.logout(token);
        return super.success();
    }

    /**
     * 获取会话
     * @return
     */
    @ApiOperation(value = "获取会话")
    @RequestMapping(value = "/info", method = {RequestMethod.POST})
    public ApiRest info(@RequestParam("token") String token) {
        SysUserLoginDTO respDTO = baseService.token(token);
        return success(respDTO);
    }

    /**
     * 修改用户资料
     * @return
     */
    @ApiOperation(value = "修改用户资料")
    @RequestMapping(value = "/update", method = {RequestMethod.POST})
    public ApiRest update(@RequestBody SysUserDTO reqDTO) {
        baseService.update(reqDTO);
        return success();
    }


    /**
     * 保存或修改系统用户
     * @return
     */
    @ApiOperation(value = "保存或修改")
    @RequestMapping(value = "/save", method = {RequestMethod.POST})
    public ApiRest save(@RequestBody SysUserSaveReqDTO reqDTO) {
        baseService.save(reqDTO);
        return success();
    }


    /**
     * 批量删除
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "批量删除")
    @RequestMapping(value = "/delete", method = { RequestMethod.POST})
    public ApiRest edit(@RequestBody BaseIdsReqDTO reqDTO) {
        //根据ID删除
        baseService.removeByIds(reqDTO.getIds());
        return super.success();
    }

    /**
     * 分页查找
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "分页查找")
    @RequestMapping(value = "/paging", method = { RequestMethod.POST})
    public ApiRest<IPage<SysUserDTO>> paging(@RequestBody PagingReqDTO<SysUserDTO> reqDTO) {

        //分页查询并转换
        IPage<SysUserDTO> page = baseService.paging(reqDTO);
        return super.success(page);
    }

    /**
     * 修改状态
     * @param reqDTO
     * @return
     */
    @ApiOperation(value = "修改状态")
    @RequestMapping(value = "/state", method = { RequestMethod.POST})
    public ApiRest state(@RequestBody BaseStateReqDTO reqDTO) {

        // 条件
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .in(SysUser::getId, reqDTO.getIds())
                .ne(SysUser::getUserName, "admin");


        SysUser record = new SysUser();
        record.setState(reqDTO.getState());
        baseService.update(record, wrapper);

        return super.success();
    }


    /**
     * 保存或修改系统用户
     * @return
     */
    @ApiOperation(value = "学员注册")
    @RequestMapping(value = "/reg", method = {RequestMethod.POST})
    public ApiRest<SysUserLoginDTO> reg(@RequestBody SysUserDTO reqDTO) {
        SysUserLoginDTO respDTO = baseService.reg(reqDTO);
        return success(respDTO);
    }

    /**
     * 快速注册，如果手机号存在则登录，不存在就注册
     * @return
     */
    @ApiOperation(value = "快速注册")
    @RequestMapping(value = "/quick-reg", method = {RequestMethod.POST})
    public ApiRest<SysUserLoginDTO> quick(@RequestBody SysUserDTO reqDTO) {
        SysUserLoginDTO respDTO = baseService.quickReg(reqDTO);
        return success(respDTO);
    }

    /**
     *导出
     * @return
     */
    @RequestMapping("/export")
    public ApiRest export(HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        List<SysUserDTO> a = baseService.find();
        String[] title={"序号ID","用户名","姓名","角色","创建时间","状态"};
        String filename="用户数据.xls";
        response.setHeader("Content-Disposition","attachment; filename="+filename);
        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("用户表");
            //创建row
            HSSFRow row = sheet.createRow(0);
            for (int i = 0; i < title.length ; i++) {
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(title[i]);
            }
            for (int i = 1; i < a.size()+1; i++) {
                HSSFRow row1 = sheet.createRow(i);
                SysUserDTO e = a.get(i - 1);
                HSSFCell cell = row1.createCell(0);
                cell.setCellValue(e.getId());
                HSSFCell cell1 = row1.createCell(1);
                cell1.setCellValue(e.getUserName());
                HSSFCell cell2 = row1.createCell(2);
                cell2.setCellValue(e.getRealName());
                HSSFCell cell3 = row1.createCell(3);
                cell3.setCellValue(e.getRoleIds());
                HSSFCell cell4 = row1.createCell(4);
                Date date = e.getCreateTime();
                SimpleDateFormat dsf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateF = dsf.format(date);
                cell4.setCellValue(dateF);
                HSSFCell cell5 = row1.createCell(5);
                cell5.setCellValue(e.getState());
            }
            ServletOutputStream out = response.getOutputStream();
            workbook.write(out);
            out.close();
        } catch (FileNotFoundException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
// TODO Auto-generated catch block
            e.printStackTrace();
//        } catch (ParseException e) {
//            e.printStackTrace();
        }
        return success();
    }

    /**
     * 导入Excel
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "import")
    public ApiRest importFile(@RequestParam("file") MultipartFile file) {

        try {

            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<UserDTO> list = ei.getDataList(UserDTO.class);

            // 校验数据
            this.checkExcel(list);

            // 导入数据条数
            baseService.importExcel2(list);

            // 导入成功
            return super.success();

        } catch (IOException e) {

        } catch (IllegalAccessException e) {

        } catch (InstantiationException e) {

        } catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException e) {
            e.printStackTrace();
        }

        return super.failure();
    }

    //校验excel
    private void checkExcel(List<UserDTO> list) {
        // 约定第三行开始导入
        int line = 3;
        StringBuffer sb = new StringBuffer();

        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException(1, "您导入的数据似乎是一个空表格！");
        }
        for (UserDTO item : list) {
            String username = item.getUserName();
            String pwd=item.getPassword();
            String real=item.getRealName();
            String dep=item.getDepartId();
            String role=item.getRoleIds();

            if (username == null||username.length()>20) {
                sb.append("第" + line + "行，用户名为空或格式有误！<br>");
            }

            if (real == null ||real.length()>20 ) {
                sb.append("第" + line + "行，真实姓名为空或格式有误！<br>");
            }
            if (pwd== null ||pwd.length()>20) {
                sb.append("第" + line + "行，密码为空或格式有误<br>");
            }

            if (role==null ||role.length()>20) {
                sb.append("第" + line + "行，角色名称为空或格式有误<br>");
            }

            if (dep==null ||dep.length()>20) {
                sb.append("第" + line + "行，部门名称为空或格式有误<br>");
            }

            String no=sysDepartService.find(dep);
            if (no==null) {
                sb.append("第" + line + "行，部门名称不存在<br>");
            }
            line++;
        }

        // 存在错误
        if (!"".equals(sb.toString())) {
            throw new ServiceException(1, sb.toString());
        }
    }

    /**
     * 下载导入用户数据模板
     */
    @ResponseBody
    @RequestMapping(value = "import/template")
    public ApiRest importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = "用户导入模板.xlsx";
            List<UserDTO> list = Lists.newArrayList();

            UserDTO l1 = new UserDTO();
            l1.setUserName("用户名");
            l1.setRealName("真实姓名");
            l1.setPassword("密码");
            l1.setRoleIds("角色");
            l1.setDepartId("部门");

            UserDTO l2 = new UserDTO();
            l1.setUserName("测试1");
            l1.setRealName("测试人员");
            l1.setPassword("123");
            l1.setRoleIds("student");
            l1.setDepartId("后端部门");

            list.add(l1);
            list.add(l2);

            new ExportExcel("用户数据", UserDTO.class, 1).setDataList(list).write(response, fileName).dispose();
            return super.success();
        } catch (Exception e) {
            return super.failure("导入模板下载失败！失败信息："+e.getMessage());
        }
    }



}
